<template>
  <el-card>
    <template #header><h2>为客户设置护理级别</h2></template>

    <el-form :model="form" label-width="100px" class="toolbar">
      <el-form-item label="客户ID">{{ form.customerId }}</el-form-item>
      <el-form-item label="选择级别">
        <el-select v-model="form.careLevelId" placeholder="请选择级别">
          <el-option
            v-for="l in levels"
            :key="l.id"
            :label="l.levelName"
            :value="l.id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="loadProjects">加载项目</el-button>

    <el-table
      v-if="projects.length > 0"
      :data="projects"
      stripe
      style="margin-top:16px;"
    >
      <el-table-column prop="name" label="项目名称" />
      <el-table-column prop="cycle" label="周期" />
      <el-table-column prop="times" label="频次" />

      <!-- 购买数量 -->
      <el-table-column label="购买数量">
        <template #default="{ row }">
          <el-input-number v-model="row.quantity" min="1" />
        </template>
      </el-table-column>

      <!-- 服务到期日期，可选 -->
      <el-table-column label="服务到期">
        <template #default="{ row }">
          <el-date-picker
            v-model="row.expireDate"
            type="date"
            placeholder="选择日期（可选）"
            style="width: 160px;"
          />
        </template>
      </el-table-column>
    </el-table>

    <div style="margin:20px 0 0 0;">
      <el-button
        type="primary"
        :disabled="projects.length === 0"
        @click="confirmAssign"
      >
        确认设置并购买
      </el-button>
      <el-button @click="goBack">取消</el-button>
    </div>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, inject } from 'vue'
import qs from 'qs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'

const axios = inject('axios')
const router = useRouter()
const route = useRoute()

// 表单与数据
const form = reactive({ customerId: null, careLevelId: null })
const levels = ref([])
const projects = ref([])

// 加载级别
async function loadLevels() {
  const resp = await axios.get('/CareLevelController/queryByStatus', {
    params: { status: 1, cur: 1, number: 999 }
  })
  levels.value = resp.data.data
}

// 加载级别对应项目，并初始化 quantity 和 expireDate 默认空
async function loadProjects() {
  if (!form.careLevelId) {
    return ElMessage.warning('请选择护理级别')
  }
  const resp = await axios.get('/CareLevelProjectController/getProjectsByLevel', {
    params: { careLevelId: form.careLevelId }
  })
  projects.value = resp.data.data.map(p => ({
    ...p,
    quantity: 1,
    expireDate: null  // 用户可选填
  }))
}

function formatDate(d) {
  const pad = n => (n < 10 ? '0' + n : '' + n)
  return d.getFullYear() + '-'
    + pad(d.getMonth() + 1) + '-'
    + pad(d.getDate()) + ' '
    + pad(d.getHours()) + ':'
    + pad(d.getMinutes()) + ':'
    + pad(d.getSeconds())
}


async function confirmAssign() {
  if (!form.careLevelId) {
    return ElMessage.warning('请选择护理级别')
  }

  // 查询客户当前已购买的 source=2 项目
  const existResp = await axios.get('/CustomerCarePlanController/searchCustomerCarePlan', {
    params: { customerId: form.customerId }
  })
  const existingPlans = existResp.data.data || []
  const existingMap = new Map()
  existingPlans.forEach(p => {
    if (p.source === 2) {
      existingMap.set(p.careProjectCode, p)
    }
  })

  // 处理冲突：逐个询问
  const toRemove = [] // 要删除旧记录
  const toKeep = new Set() // 不添加这些项目

  for (const p of projects.value) {
    if (existingMap.has(p.code)) {
      const answer = await ElMessageBox.confirm(
        `项目【${p.name}】客户已单独购买。\n是否覆盖已有记录？`,
        '覆盖提示',
        {
          confirmButtonText: '覆盖',
          cancelButtonText: '保留',
          type: 'warning'
        }
      ).then(() => true).catch(() => false)

      if (answer) {
        toRemove.push(p.code)
      } else {
        toKeep.add(p.code)
      }
    }
  }

  // 删除原记录（source=2 的）
  for (const code of toRemove) {
		await axios.delete('/CustomerCarePlanController/delCustomerCarePlan', {
		  params: {
			customerId: form.customerId,
			careProjectCode: code
		  }
		})
  }

  // 从项目列表中移除不添加的项目（保留原记录）
  projects.value = projects.value.filter(p => !toKeep.has(p.code))

  // 设置客户级别
  await axios.post('/CustomerCareLevelController/addCustomerCareLevel', qs.stringify(form))

  // 添加护理项目
  const now = new Date()
  const defaultExpire = new Date()
  defaultExpire.setMonth(now.getMonth() + 3)

  for (const p of projects.value) {
    const plan = {
      customerId: form.customerId,
      careProjectCode: p.code,
      purchaseDate: formatDate(now),
      quantity: p.quantity,
      expireDate: formatDate(p.expireDate ? new Date(p.expireDate) : defaultExpire),
      status: 1,
      source: 1
    }
    await axios.post('/CustomerCarePlanController/addCustomerCarePlan', qs.stringify(plan))
  }

  ElMessage.success('设置成功，已为客户批量购买项目')
  router.push({ path: '/CustomerCareConfig' })
}
// 返回
function goBack() {
  router.back()
}

// 初始化
onMounted(async () => {
  form.customerId = Number(route.query.customerId)
  await loadLevels()
})
</script>

<style scoped>
.toolbar { margin-bottom: 16px; }
</style>
